import apiHome from 'Api/home.js';
import * as types from './types.js';
import vue from 'vue';

const state = () => ({
	scrollTop: 0,
	isFirst: true,
	feedList: []
});

const getters = {
};

const actions = {
	[types.saveScrollTop] ({ commit }, scrollTop) {
		commit(types.saveScrollTop, scrollTop);
	},
	[types.getFeedList] ({ commit, state }, cookies) {
		if (vue.prototype.$isServer) {
			return apiHome.getIndexDataServer(cookies).then((res) => {
				commit(types.getFeedListSuccess, { res });
			}, (err) => {
				commit(types.getFeedListFail, { err });
				return Promise.reject();
			});
		}
		else {
			return apiHome.getIndexData().then((res) => {
				commit(types.getFeedListSuccess, { res });
			}, (err) => {
				commit(types.getFeedListFail, { err });
				return Promise.reject();
			});
		}
	},
	[types.submitDislike] ({ commit }, { id, dislike_list }) {
		// 提交用户不喜欢的类别
		commit(types.submitDislikeSuccess, { id });
	},
	[types.submitNotInterested] ({ commit }, { type }) {
		// 提交用户不感兴趣的类别
		commit(types.submitNotInterestedSuccess, { type });
	}
};

const mutations = {
	[types.saveScrollTop] (state, scrollTop) {
		state.scrollTop = scrollTop;
	},
	[types.getFeedListSuccess] (state, { res }) {
		if (state.isFirst) {
			state.isFirst = false;
		}
		state.feedList = state.feedList.concat(res.data);
	},
	[types.getFeedListFail] (state, { err }) {
		console.log(err);
	},
	[types.submitDislikeSuccess] (state, { id }) {
		state.feedList = state.feedList.filter((item) => {
			return item.id !== id;
		});
	},
	[types.submitNotInterestedSuccess] (state, { type }) {
		state.feedList = state.feedList.filter((item) => {
			return item.type !== type;
		});
	}
};

export default {
	state,
	getters,
	actions,
	mutations
};
